package com.imflea.zero.utils;

import lombok.Getter;
import lombok.ToString;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author zhaoyang
 * @version 1.0
 * @project farmplus-service
 * @package com.imflea.zero.utils
 * @filename 创建时间: 2021/9/27
 * @description
 * @copyright Copyright (c) 2021 中国软件与技术服务股份有限公司
 */
public final class AdoptCouponUtil {

    private AdoptCouponUtil() {
        throw new IllegalStateException("Util class no instance ");
    }

    // 盐值千万不要修改
    private static final String SALT = "THERE IS NO SMOKE WITHOUT FIRE";

    public static  Card generateCard(String prefix, int seq) {

        String batch = formattedDate("yyMMdd");
        String code = String.format("%s%s%05d", prefix, batch, seq);

        byte[] magic = JdkHmacUtils.getHmacMd5Key();
        String secret = generateSecret(SALT, magic);

        return new Card(JdkHmacUtils.encodeHex(magic), batch, code, secret);
    }

    // 格式化日期
    public static String formattedDate(String outputFormat) {
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputFormat);
        return LocalDateTime.now().format(outputFormatter);
    }

    // 生成密钥
    private static String generateSecret(String magic, byte[] md5) {
        String hmacMd5Encrypt = JdkHmacUtils.encryptHmacMD5(magic.getBytes(StandardCharsets.UTF_8), md5);
        String secret = hmacMd5Encrypt.substring(0, 8);
        return secret;
    }

    @ToString
    @Getter
    public static class Card {
        private String magic;
        private String code;
        private String secret;
        private String batch;

        public Card(String magic, String batch, String code, String secret) {
            this.magic = magic;
            this.batch = batch;
            this.code = code;
            this.secret = secret;
        }
    }

    public static void main(String[] args) {
        String date = formattedDate("yyMMdd");
        System.out.println(date);
    }
}
